# encoding:utf-8

from pexpect import EOF
from pexpect import TIMEOUT
from pexpect import spawn
from app.extensions import log, db
from config import BeetleConfig
from app.modules.apps.models import App
import app

def checkStartLog(app_id = None, log_file = None):
    """
    执行install时，应用启动按照
    :param app:
    :param app_id:
    :param log_file:
    :return:
    """
    log.info('Checking %s startup logging....' % app_id)
    flask_app = app.create_app()
    with flask_app.app_context():
        _app = App.query.filter_by(app_id = app_id).filter_by(disabled = 0).first()
        if _app is None:
            log.error('根据 %s 获取应用信息为none.' % app_id)
            return

        _tail_log_cmd = 'tail -f %s' % log_file

        child = spawn(_tail_log_cmd)

        p_success = r"INFO: Server startup in \d* ms"
        p_exception = r".*Exception:.*"
        p_exception2 = r"SEVERE: Context \[/.*] startup failed due to previous errors"

        # expect刷日志会稍微有点延迟, 大概比实际日志的输出慢了半分钟左右.
        index = child.expect(
            pattern = [EOF, TIMEOUT, p_success, p_exception, p_exception2],
            timeout = BeetleConfig.UCLOUD_APP_CHECKLOG_TIMEOUT)
        if index == 1:
            log.error('启动%s 超过%d秒, 请检查应用启动日志和dubbo服务, 确认应用是否正确启动.' % (app_id, BeetleConfig.UCLOUD_APP_CHECKLOG_TIMEOUT))
            _app.status = 'unavailable'
            _app.last_msg = '[ERROR]启动%s 超过%d秒, 请检查应用启动日志和dubbo服务, 确认应用是否正确启动.' % (
                app_id, BeetleConfig.UCLOUD_APP_CHECKLOG_TIMEOUT)
        elif index > 2:
            log.error('在%s的启动日志中发现了Exception关键字, 可能启动失败, 也可能只是警告.请检查应用启动日志和dubbo控制台, 确认应用是否启动正常.' % app_id)
            _app.status = 'unavailable'
            _app.last_msg = '[ERROR]在%s的启动日志中发现了Exception关键字, 可能启动失败, 也可能只是警告.请检查应用启动日志和dubbo控制台, 确认应用是否启动正常.' % app_id
        else:
            _app.status = 'ready'
            _app.last_msg = '[INFO]%s_restart 执行完毕.' % app_id

        db.session.commit()

        log.info('Checking %s startup log end' % app_id)
